import request from "@/utils/rquest";
import { useUserStore } from "@/stores/user";
import md5 from "md5";
import sha1 from "crypto-js/sha1";

// 签名生成工具函数
function generateSignParams(config) {
  // 这里的 APP_ID 与 APP_SECRET 请替换为真实值
  const APP_ID = "azRnLvxl";
  const APP_SECRET = "76d9baa27803da36d07ec4972fd041b32fcec40d"; // 来自后端配置

  const timestamp = Date.now().toString();
  const nonce =
    Math.random().toString(36).substring(2, 15) +
    Math.random().toString(36).substring(2, 15);

  const params = JSON.parse(JSON.stringify(config?.params || {}));
  // 与对方签名逻辑保持一致：不排序，按原始键顺序拼接
  const query = Object.keys(params)
    .map((key) => `${key}=${params[key]}`)
    .join("&");

  const data =
    !config?.data || config?.data instanceof FormData
      ? ""
      : JSON.stringify(config.data || "");

  // const queryError = /error/.test(window.location.href)
  //   ? `&error=${Date.now()}`
  //   : "";
  const queryError = "";

  const signature = `${query}${queryError}${data}appId=${APP_ID}&nonce=${nonce}&timestamp=${timestamp}${APP_SECRET}`;
  const signatureMd5 = md5(sha1(signature).toString()).toString();
  const signatureParam = `appId=${APP_ID}&nonce=${nonce}&timestamp=${timestamp}`;

  return {
    timestamp,
    nonce,
    sign: signatureMd5,
    appParam: signatureParam,
    appId: APP_ID,
  };
}

// 添加通用请求头
export function addCommonHeaders(
  config,
  isLogin = false,
  isDetailedBattery = false
) {
  const { sign, appParam, appId } = generateSignParams(config);
  const userStore = useUserStore();

  // 通用头部
  config.headers = {
    ...(config.headers || {}),
    "Accept-Language": "zh-CN",
    // 按对方约定的大小写
    "Cfmoto-X-Sign": sign,
    "Cfmoto-X-Param": appParam,
    "Cfmoto-X-Sign-Type": "0",
    appid: appId,
    "x-app-info":
      "MOBILE|Android|9|KLICEN_APP|2.2.5|Dalvik/2.1.0 (Linux; U; Android 9; V2199GA Build/PQ3A.190705.09121602)|720*1280|1|100|wifi|vivo",
  };

  // 登录时使用Basic认证
  if (isLogin) {
    config.headers.Authorization = "Basic bWNrOjEyMzQ1Ng==";
    config.headers["Content-Type"] = "application/json";
  } else {
    // 其他API调用使用token
    config.headers.Authorization = `bearer ${userStore.userInfo?.token || ""}`;
  }

  return config;
}

// 获取验证码
export function getVerifyCode(phone) {
  const config = {
    url: `/v1.0/mine/cfmotoservermine/authCode/${phone}`,
    method: "get",
  };

  return request(addCommonHeaders(config, true));
}

// 登录
export function login(data) {
  const loginData = {
    authCode: data.code,
    phone: data.phone,
    city: "110101",
    latitude: "39.916296",
    longitude: "116.410344",
    province: "",
    referralCode: "",
  };

  const config = {
    url: "/v1.0/mine/cfmotoservermine/user/loginByPhone",
    method: "post",
    data: loginData,
  };

  return request(addCommonHeaders(config, true));
}
